/*
 * Copyright (c) 2022-2022 All rights Reserved.
 */

package com.driving.core.base;

import java.util.Arrays;
import java.util.Map;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.driving.core.exception.DrivingException;
import com.driving.core.util.ConfigReader;
import com.driving.core.util.Constant;
import com.driving.core.util.Constant.Audience;
import com.driving.core.util.JsonWebToken;
import com.driving.core.util.MessageType.ExceptionType;

import lombok.extern.slf4j.Slf4j;

/**
 * 基础Controller
 *
 * @param <S> 声明的服务类型
 * @param <T> 需要操作的对象
 * @author SAGITTAR
 * @since 2017
 */
@Slf4j
public abstract class BaseController<S extends IBaseService<T>, T extends AbstractModel<T>> {

    @Autowired
    protected S baseService;

    @Autowired
    protected ConfigReader configReader;

    /**
     * 保证参数非空，采用两组参数避免集合为空
     *
     * @param first first
     * @param others others
     * @return 保证参数非空
     */
    protected static boolean validateAllParams(Object first, Object... others) {
        for (Object param : Arrays.asList(first, others)) {
            if (Objects.isNull(param)) {
                log.warn("the param is null");
                return false;
            }
            if (param instanceof CharSequence && StringUtils.isBlank((CharSequence) param)) {
                log.warn("the param is isBlank");
                return false;
            }
        }
        return true;
    }

    /**
     * 获取当前请求的ID，如果请求过时，则返回<code>null</code>
     *
     * @param token token
     * @param audience audience
     * @return 获取当前请求的ID
     */
    protected Integer getCorrespondingIdByRequest(String token, Audience audience) {
        Integer correspondingId = null;
        Map<String, String> tokenMap = JsonWebToken.parse(token, audience);
        if (Objects.nonNull(tokenMap) && tokenMap.containsKey(Constant.ID)) {
            correspondingId = Integer.parseInt(tokenMap.get(Constant.ID));
        }
        log.debug("getCorrespondingIdByRequest audience {}, correspondingId {}", audience, correspondingId);
        return correspondingId;
    }

    /**
     * 强制获取当前请求的ID，如果请求过时，则抛出异常
     *
     * @param token token
     * @param audience audience
     * @return 强制获取当前请求的ID
     */
    protected int getNonNullCorrespondingIdByRequest(String token, Audience audience) {
        Integer correspondingId = getCorrespondingIdByRequest(token, audience);
        if (Objects.isNull(correspondingId)) {
            log.error("getNonNullCorrespondingIdByRequest audience {}, correspondingId is null", audience);
            throw new DrivingException(configReader.getExceptionMessage(ExceptionType.NOT_LOGIN));
        }
        return correspondingId;
    }
}
